package utils

import (
	pb "gitee.com/hakwolf/taibak/internal/modules/rpc/proto"
	"github.com/go-sql-driver/mysql"
	"io/ioutil"
	"log"

	"os/exec"
	"strconv"
)

func BackupMySqlDb(req *DbTaskRequest, dumpDir, dumpFilenameFormat string) (error, string) {

	//func Exemysqlbak(req *pb.DbTaskRequest,dumpDir,dumpFilenameFormat string) (errs error) {
	// Open connection to database

	config := mysql.NewConfig()
	config.User = req.Ac
	config.Passwd = req.Pd
	config.DBName = req.Dbname
	config.Net = "tcp"
	config.Addr = req.Dip + ":" + strconv.FormatInt(req.Port, 10)
	var cmd *exec.Cmd

	port := strconv.FormatInt(req.Port, 10)

	//if tableName == "" {
	cmd = exec.Command(dumpDir, "--opt", "-h"+req.Dip, "-P"+port, "-u"+req.Ac, "-p"+req.Pd, req.Dbname)
	/*	} else {
			cmd = exec.Command("mysqldump", "--opt", "-h"+host, "-P"+port, "-u"+user, "-p"+password, databaseName, tableName)
		}
	*/
	stdout, err := cmd.StdoutPipe()
	if err != nil {
		log.Fatal(err)
		return err, ""
	}

	if err := cmd.Start(); err != nil {
		log.Fatal(err)
		return err, ""
	}

	bytes, err := ioutil.ReadAll(stdout)
	if err != nil {
		log.Fatal(err)
		return err, ""
	}
	//now := time.Now().Format("20060102150405")
	var backupPath string
	//if tableName == "" {
	backupPath = dumpFilenameFormat //backupPath = sqlPath+databaseName+"_"+now+".sql"
	/*	} else {
		backupPath = sqlPath+databaseName+"_"+tableName+"_"+now+".sql"
	}*/
	err = ioutil.WriteFile(backupPath, bytes, 0644)

	if err != nil {
		panic(err)
		return err, ""
	}
	return nil, backupPath
}

func BackupMySqlDb2(req *pb.DbTaskRequest, dumpDir, dumpFilenameFormat string) (error, string) {

	//func Exemysqlbak(req *pb.DbTaskRequest,dumpDir,dumpFilenameFormat string) (errs error) {
	// Open connection to database

	config := mysql.NewConfig()
	config.User = req.Ac
	config.Passwd = req.Pd
	config.DBName = req.Dbname
	config.Net = "tcp"
	config.Addr = req.Dip + ":" + strconv.FormatInt(req.Port, 10)
	var cmd *exec.Cmd

	port := strconv.FormatInt(req.Port, 10)

	//if tableName == "" {
	cmd = exec.Command(dumpDir, "--opt", "-h"+req.Dip, "-P"+port, "-u"+req.Ac, "-p"+req.Pd, req.Dbname)
	/*	} else {
			cmd = exec.Command("mysqldump", "--opt", "-h"+host, "-P"+port, "-u"+user, "-p"+password, databaseName, tableName)
		}
	*/
	stdout, err := cmd.StdoutPipe()
	if err != nil {
		log.Fatal(err)
		return err, ""
	}

	if err := cmd.Start(); err != nil {
		log.Fatal(err)
		return err, ""
	}

	bytes, err := ioutil.ReadAll(stdout)
	if err != nil {
		log.Fatal(err)
		return err, ""
	}
	//now := time.Now().Format("20060102150405")
	var backupPath string
	//if tableName == "" {
	backupPath = dumpFilenameFormat //backupPath = sqlPath+databaseName+"_"+now+".sql"
	/*	} else {
		backupPath = sqlPath+databaseName+"_"+tableName+"_"+now+".sql"
	}*/
	err = ioutil.WriteFile(backupPath, bytes, 0644)

	if err != nil {
		panic(err)
		return err, ""
	}
	return nil, backupPath
}
